<?php

function deleteChatSession()
{
    if (!App::getUser('user'))
    {
        return;
    }
    $sDir = App::getParam('chat.path');
	if ($dh = opendir($sDir)) 
	{
        while (($sFile = readdir($dh)) !== false) 
       	{
            if('users'==substr($sFile,0,5))
            {
	            $aRows = unserialize(file_get_contents($sDir.$sFile));
            	foreach($aRows as $sUser=>$iTime)
		        {
		            if($sUser==App::getUser('user'))
		            {
		                unset($aRows[$sUser]);
                        if($hFile = fopen($sDir.$sFile,'w'))
                        {
                            fwrite($hFile, serialize($aRows));
                            fclose($hFile);
                        }
                        break;
		            }
		        }
			}
        }
        closedir($dh);
    }
}

/**
 * Get chat messages
 *
 * @param array $aArg (0 - shoutbox default; 1-full chat)
 * @return object
 */
function getChatText($aArg = 0, $iRoomId = 0, $bNoRefresh = false, $bAjax = true)
{
    if ($bAjax)
    {
    	$oRespX = new xajaxResponse();
		if ( !App::getUser('user') )
		{
			$oRespX->addScript("window.close();");
			return $oRespX;
		}
    }
   

    $sTxt = '';
    $aRows = array();
    $sChatFile = App::getParam('chat.path').'room'.$iRoomId.'.txt';
    if(file_exists($sChatFile)) 
        $aRows = unserialize (file_get_contents($sChatFile));
    if(is_array($aRows))
    {
    	if(App::getParam('chat_display_today'))
    	{
    		$iTimeLimit = time() - 86400;
    		for($i=count($aRows)-1;$i>0 AND $aRows[$i]['time']<$iTimeLimit;--$i)
    		{
    			unset($aRows[$i]);
    		}
    	}
    	foreach ($aRows as $aRow)
       	{
       		$sTxt .= '<div style="padding:2px;"><span style="font-size:7pt;">['.date('H:i',$aRow['time']).'] </span>';
	           	if ( $aArg )
	           	{
	           	   $sTxt .= '<a href="javascript:void(0);" onclick="window.opener.document.location.href=\''.App::makeUrl('public.user', array('name'=>$aRow['user'])).'\';window.opener.focus();">'.$aRow['user'].'</a>: ';
			   	}
	           	else
	           	{
					  $sTxt .= '<b><a href="'.App::makeUrl('public.user', array('name'=>$aRow['user'])).'" target="_blank">'.$aRow['user'].'</a>: </b>';
			   	}
	           	$sTxt .= '<span>'. $aRow['text'] .'</span></div>';
       	}
	}

	if ($bAjax)
	{
		$oRespX->addScript(" var bScrollInBottom = document.getElementById('chat_content_div').scrollTop == document.getElementById('chat_content_div').scrollHeight-parseInt(document.getElementById('chat_content_div').style.height);");
    	$aArg == 0 ? $oRespX->addAssign("shortchat","innerHTML", $sTxt) : $oRespX->addAssign("fullchat","innerHTML", $sTxt);
    	if ( $aArg )
    	{
    		$oRespX->addScript(" if(bScrollInBottom) document.getElementById('chat_content_div').scrollTop = document.getElementById('chat_content_div').scrollHeight;");
    	}
    	return $oRespX;
    }
    else
    {
    	return $sTxt;
    }
}

function getOnlineUser($iRoomId = 0, $bAjax = true)
{
    if ($bAjax)
    {
    	$oRespX = new xajaxResponse();
		if ( !App::getUser('user') )
		{
			$oRespX->addScript("window.close();");
			return $oRespX;
		}
    }
    $sDiv = '';
    $iTimeout = time() - App::getSetting('max_time_online') * 60;

	$sUserFileName = App::getParam('chat.path').'users'.$iRoomId.'.txt';
	if(file_exists($sUserFileName))
	{
		$aRows = unserialize(file_get_contents($sUserFileName));
		foreach($aRows as $sUser=>$iTime)
		{
			if($iTime<$iTimeout)
				unset($aRows[$sUser]);
		}
	}else{
		$aRows = array();
	}
	$aRows[App::getUser('user')] = time();
	if($hFile = fopen($sUserFileName,'w'))
	{
		fwrite($hFile, serialize($aRows));
		fclose($hFile);
	}
	
	$sImageUrl = App::getParam('user.pic.url');
	$sImagePath = App::getParam('user.pic.path');
	$iSize = 20;
	$sDefUrl = App::getParam('url').'design/pic/noimage_'.$iSize.'.jpg';
	$iNum = 0;
    foreach($aRows as $sUser => $iTime)
    {
		$sStyle = (is_int($iNum++/2)) ? ' class="border13"' : '';
		$sUserUrl = App::makeUrl('public.user', array('name' => $sUser));
        $sDiv .= '<table style="width:100%;" cellpadding="1" cellspacing="1"'.$sStyle.'>
           <tr>
			<td style="width:30px; text-align:center;">
				<a href="javascript:void(0);" style="cursor:pointer;" onclick="window.opener.document.location.href=\''. $sUserUrl .'\';window.opener.focus();">
        		<img src="'.
                (file_exists($sImagePath.$sUser.'_'.$iSize.'.jpg')? $sImageUrl.$sUser.'_'.$iSize.'.jpg': $sDefUrl).
                '" width="20">
        		</a>
			</td><td>
				<a href="javascript:void(0);" style="cursor:pointer;" onclick="window.opener.document.location.href=\''. $sUserUrl .'\';window.opener.focus();">
				'.$sUser.'
				</a>
			</td>
			</tr>
			</table>';
    }


	if ($bAjax)
	{
    	$oRespX->addAssign("onlineuser","innerHTML", $sDiv);
	    return $oRespX;
	}
	else
	{
		return $sDiv;
	}
}

/**
 * Post Message Text
 *
 * @param array $aFormValue (Post form value)
 * @return object
 */
function processForm($aFormValue, $iRoomId = 0, $bIsChat = false)
{
    $oRespX = new xajaxResponse();
	if ( !App::getUser('user') )
	{
		$oRespX->addScript("window.close();");
		return $oRespX;
	}
    
    define('PHPFOX_PROTECT_IMG', true);

	App::loadClass('Text');
    $oTxt = new Text();

    $sText = $oTxt->preParseChat($aFormValue['sTxt']);  

	if ( empty($sText) )
	{
		$oRespX->addScript("tinyMCE.execCommand('mceSetContent',false, '')");
		return $oRespX;
	}

	$iLastTime = $_SESSION['Chat.iLastTime'];
	$iLastTimeStamp = (time()-$iLastTime);
	if($iLastTimeStamp < App::getSetting('chat_flood'))
    {
		if (!$iLastTimeStamp)
		{
    		return $oRespX;
		}
		else
		{
			$oRespX->addScript("tinyMCE.execCommand('mceSetContent',false, '" . $aFormValue['sTxt'] . "')");
			$oRespX->addAlert(App::format('Mod_Site.flood_hold', App::getSetting('chat_flood')));
			return $oRespX;
		}
    }

    $sText = $oTxt->_splitString($sText, App::getParam('chat_wrap'), "<br />\n");
    $sText = $oTxt->parsePostChat($sText);
    $sText = $oTxt->utf8ToUnicode($sText);

    $iTime = time();
    $sTxt = '<div style="padding:2px;"><span style="font-size:7pt;">['.date('H:i',$iTime).'] </span><a href="javascript:void(0);" onclick="window.opener.document.location.href=\''.App::makeUrl('public.user', array('name'=>App::getUser('user'))).'\'">'.App::getUser('user').'</a>: '.$sText.'</div>';
	$oRespX->addScript("document.getElementById('fullchat').innerHTML = document.getElementById('fullchat').innerHTML + '". str_replace("'", "\'", $sTxt) ."'; document.getElementById('chat_content_div').scrollTop = document.getElementById('chat_content_div').scrollHeight;");
	
	$_SESSION['Chat.iLastTime'] = $iTime;
	$sChatFileName = App::getParam('chat.path').'room'.$iRoomId.'.txt';
	$aRows = array();
	if(file_exists($sChatFileName))
	{
		$aRows = array_slice(unserialize(file_get_contents($sChatFileName)), -50);
	}
	$aRows[] = array('user'=>App::getUser('user'), 'text'=>$sText, 'time'=>$iTime, 'ip'=>$_SERVER['REMOTE_ADDR'] );
	if($hFile = fopen($sChatFileName,'w'))
	{
		fwrite($hFile, serialize($aRows));
		fclose($hFile);
	}

    return $oRespX;
}

function _chatMembersOnly(&$oRespX)
{
	if ( !App::getUser('user') )
	{
		$oRespX->addScript("window.close();");
		return $oRespX;
	}
}

?>